package com.github.llyb120.stock.ctrl;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.Json;
import com.github.llyb120.json.Obj;
import com.github.llyb120.namilite.NamiBaseController;
import com.github.llyb120.namilite.core.Async;
import com.github.llyb120.stock.Ctrl;

import java.io.File;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.github.llyb120.json.Json.*;
import static com.github.llyb120.stock.Ctrl.*;

public class test extends NamiBaseController {

    public Object download() throws InterruptedException {
        downloads();
        return true;
    }

    public Object a(){
        return "abbff";
    }

    public Object test() {
        Async.execute(() -> {
            try{
                downloads();
//                save();
                System.out.println("ok");
            } catch (Exception e){
            }
        });
        return "ok";
    }

    public void save() throws InterruptedException {
        for (File file : Ctrl.dir.listFiles()) {
            if(!file.getName().endsWith(".csv")){
                continue;
            }
            String code = file.getName().replace(".csv", "");
            saveCsv(code);
        }
    }
    
    private BigDecimal toBigDecimal(String str){
        try{
            return new BigDecimal(str);
        } catch (Exception e){
            return BigDecimal.ZERO;
        }
    }

    private void saveCsv(String code){
//        System.out.println(String.format("saving %s to database...", code));
//        CsvData data = CsvUtil.getReader().read(new File(Ctrl.dir, code + ".csv"), Charset.forName("GBK"));
//        List<CsvRow> rows = data.getRows();
//        if(rows.size() <= 1){
//            return;
//        }
//        Connection connection = null;
//        PreparedStatement statement = null;
//        try {
//            connection = dataSource.getConnection();
//            connection.setAutoCommit(false);
//            connection.createStatement().execute(String.format("delete from stock where code = '%s'", code));
//            statement = connection.prepareStatement("insert into stock(id, name, code, high_price, low_price, begin_price, end_price, stock_date, exchange, trade_count, trade_money) values(?,?,?,?,?,?,?,?,?,?,?)");
//
//            for (int i = 1; i < rows.size(); i++) {
//                CsvRow row = rows.get(i);
//                statement.setString(1, IdUtil.objectId());
//                statement.setString(2, row.get(2));
//                statement.setString(3, code);
//                statement.setBigDecimal(4, toBigDecimal(row.get(4)));
//                statement.setBigDecimal(5, toBigDecimal(row.get(5)));
//                statement.setBigDecimal(6, toBigDecimal(row.get(6)));
//                statement.setBigDecimal(7, toBigDecimal(row.get(3)));
//                statement.setDate(8, DateUtil.parseDate(row.get(0)).toSqlDate());
//                statement.setBigDecimal(9, toBigDecimal(row.get(10)));//DateUtil.parseDate(row.get(0)).toSqlDate());
//                statement.setBigDecimal(10, toBigDecimal(row.get(11)));//DateUtil.parseDate(row.get(0)).toSqlDate());
//                statement.setBigDecimal(11, toBigDecimal(row.get(12)));//DateUtil.parseDate(row.get(0)).toSqlDate());
//                statement.addBatch();
//            }
//            statement.executeLargeBatch();
//            connection.commit();
//        } catch (SQLException e) {
//            e.printStackTrace();
//            try{
//                connection.rollback();
//            } catch (Exception ee){}
//        } finally {
//            try{
//                connection.setAutoCommit(true);
//            } catch (Exception e){}
//            IoUtil.closeIfPosible(connection);
//            IoUtil.closeIfPosible(statement);
//        }
//        sqlManager.insertBatch(Stock.class, arr);
    }

    private Map<String, String> codes() throws InterruptedException {
        System.out.println("downloading codes...");
        int max = 196;
//        Set<String> ret = new ConcurrentHashSet<String>();
        Map<String, String> map = new ConcurrentHashMap<>();
        ExecutorService executorService = Executors.newFixedThreadPool(16);
        for (int i = 1; i <= max; i++) {
            final int finalI = i;
            executorService.submit(() -> {
                String url = String.format("http://74.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112405901492475805081_1581665062273&pn=%d&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1581665062310", finalI);
                String str = HttpUtil.get(url);
                int start = str.indexOf("(");
                str = str.substring(start + 1, str.length() - 2);
                Obj obj = Json.parse(str);
                Arr<Obj> arr = obj.get("data.diff", Arr.class);
                arr.forEach(e -> {
                    map.put(e.ss("f12"), e.ss("f14"));
                });
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
        return map;
    }

    public void downloads() throws InterruptedException {
        File file = new File(Ctrl.dir.getParent(), Ctrl.dir.getName() + "-temp");
        FileUtil.del(file);
        file.mkdirs();
        ExecutorService executorService = Executors.newFixedThreadPool(16);
        String date =DateUtil.format(new Date(), "yyyyMMdd");
        Map<String, String> codes = codes();
        for (String code : codes.keySet()) {
            executorService.submit(() -> {
                System.out.println("downloading " + code);
                String url = String.format("http://quotes.money.163.com/service/chddata.html?&start=20120101&code=0%s&end=%s&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP", code, date);
                HttpUtil.downloadFile(url, new File(file, code + ".csv"));
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

        FileUtil.writeString(Json.stringify(codes), new File(file, "menu.json"), StandardCharsets.UTF_8);
        //覆盖原文件
        FileUtil.del(dir);
        FileUtil.move(file, dir, true);
        System.out.println("download finished");
    }
}
